﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Caching;

namespace InhollandAirPortal {
  public partial class LoginPage : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {
    }

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {
			// Aantal loginpogingen tellen
      CountLogonAttempt();
      if (NumberOfLogonAttemps() < 5) { // Na 5 pogingen niet meer proberen in te loggen
        bool Authenticated = false;
				// Login valideren
        Authenticated = ValidateLogin(LoginForm.UserName, LoginForm.Password);
        e.Authenticated = Authenticated;
        if (Authenticated == true) {
					// Bij een goede login het aantal loginpogingen resetten
          ClearLogonCounter();
          FormsAuthentication.RedirectFromLoginPage(LoginForm.UserName, false);
        }
      } else { // 5 logingpogingen; alert weergeven
        Master.FindControl("cphContent").Controls.Add(Message.ShowMessage(MessageText.Message_LoginTimeOut, MessageType.MessageType_Alert));
      }
    }

    private bool ValidateLogin(string aUserName, string aPassword) { // Login valideren
      return PortalUser.ValidateUser(aUserName, aPassword);
    }

    private int NumberOfLogonAttemps() { // Return aantal loginpogingen
      if (Cache[LoginForm.UserName] == null)
        return 0;
      return (int)Cache[LoginForm.UserName];
    }
    private void ClearLogonCounter() { // Clear aantal loginpogingen
      if (Cache[LoginForm.UserName] != null) {
        Cache.Remove(LoginForm.UserName);
      }
    }
    private void CountLogonAttempt() { // Aantal loginpogingen tellen
      if (Cache[LoginForm.UserName] == null) { // Cache toevoegen als deze niet bestaat
        Cache.Insert(LoginForm.UserName, 1, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
      } else { // Cache ophogen indien deze al bestaat
        int tries = (int)Cache[LoginForm.UserName];
        Cache.Insert(LoginForm.UserName, tries + 1, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
      }
    }
  }

}




  